package com.baizan.daka.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.baizan.base.BaseActivity
import com.baizan.daka.*
import com.baizan.daka.ui.contract.ExtensionContract
import com.baizan.daka.ui.presenter.ExtensionPresenter
import com.baizan.daka.util.PermissionDialogUtils
import com.baizan.daka.util.QrCodeUtil
import com.dianzan.daka.R
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.act_extension.*
import rx.Observable
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

class ExtensionActivity : BaseActivity<ExtensionPresenter>(), ExtensionContract.View {

    companion object {

        fun start(context: Context) {
            val intent = Intent(context, ExtensionActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val imgs = arrayListOf(R.mipmap.bg_ext_0, R.mipmap.bg_ext_1,
        R.mipmap.bg_ext_3, R.mipmap.bg_ext_4, R.mipmap.bg_ext_5)
    private val distances = arrayListOf(155, 180,180, 150, 155)
    var code: String? = null
    val logoBmp: Bitmap by lazy {
        BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
    }
    var url: String? = null
    var mPosition: Int = 0
    private val views = arrayListOf<View>()


    override fun initPresenter(): ExtensionPresenter = ExtensionPresenter(this)

    override fun layoutId(): Int = R.layout.act_extension

    override fun initData() {

    }

    override fun initView() {

        save.setOnClickListener {
            getPermissions()
        }
        back_tv.setOnClickListener {
            finish()
        }
        right.setOnClickListener {
            mViewPager.currentItem = mPosition+1
        }
        left.setOnClickListener {
            mViewPager.currentItem = mPosition-1
        }
        left.visibility =View.GONE
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                if(position == 0){
                    left.visibility =View.GONE
                }else{
                    left.visibility =View.VISIBLE
                }
                if(position == imgs.size-1){
                    right.visibility = View.GONE
                }else{
                    right.visibility = View.VISIBLE
                }
                mPosition = position
            }

        })
    }


    override fun start() {
        presenter?.getExtensionCode()
    }

    fun getPermissions() {
        val rxPermissions2 = RxPermissions(this)
        Observable.just(Any())
            .compose(rxPermissions2.ensureEach(Manifest.permission.READ_EXTERNAL_STORAGE))
            .compose(rxPermissions2.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            .subscribe { permission ->
                if (permission.granted) {
                    // 用户允许权限
                    val view = views[mPosition]
                    saveQrBitmap(view.findViewById(R.id.copy), view)
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // 用户拒绝了权限申请
                } else {
                    // 用户拒绝，并且选择不再提示
                    // 可以引导用户进入权限设置界面开启权限
                    PermissionDialogUtils().showMyDialog(this, "进入权限设置界面开启-存储权限")
                }
            }
    }

    override fun getExtensionCodeSuccess(url: String) {
        val invCodeStr = "invitationCode="
        val a = url.lastIndexOf(invCodeStr)
        if (-1 != a) {
            code = url.substring(a + invCodeStr.length, url.length)
        }
        this.url = url
        mViewPager.adapter = Adapter()
    }

    fun saveQrBitmap(copy: View, root_view: View) {
        copy.visibility = View.GONE
        val bitmap = getViewBp(root_view)
        val bitName = System.currentTimeMillis().toString() + ".jpg"
        var file: File? = null
        var fileName: String? = null
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName =
                Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName
        } else { // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName
        }
        file = File(fileName)
        if (file.exists()) {
            file.delete()
        }
        var out: FileOutputStream? = null
        try {
            out = FileOutputStream(file)
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
                // 插入图库
//                MediaStore.Images.Media.insertImage(
//                    contentResolver,
//                    file.getAbsolutePath(),
//                    bitName,
//                    null
//                )
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        // 发送广播，通知刷新图库的显示
        mContext?.let {
            it.sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.parse("file://" + fileName)
                )
            )
        }

        showToast("已保存到相册")
        copy.visibility = View.VISIBLE
    }

    inner class Adapter : PagerAdapter() {

        override fun isViewFromObject(view: View, o: Any): Boolean = view == o

        override fun getCount(): Int = imgs.size

        override fun destroyItem(container: ViewGroup, position: Int, view: Any) {
            container.removeView(view as View)
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val view =
                LayoutInflater.from(container.context).inflate(R.layout.frg_extension, null)
            view.background = resources.getDrawable(imgs[position])
            val codeIv = view.findViewById<ImageView>(R.id.code_tv)
            val codeText = view.findViewById<TextView>(R.id.code_text)
            val copy = view.findViewById<ImageView>(R.id.copy)
           val lp = codeIv.layoutParams
            lp as ConstraintLayout.LayoutParams
            lp.bottomMargin = dip2px(distances[position])

            url?.let {
                var qrBm = QrCodeUtil.createQRImage(it, dip2px(170), dip2px(170), logoBmp)
                codeIv.setImageBitmap(qrBm)
            }
            codeText.text = "我的邀请码：${code}"
            copy.setOnClickListener {
                copyContent(container.context, code)
                showToast("复制成功")
            }
            container.addView(view)
            views.add(view)
            return view

        }
    }
}





